var loginUrl = "/mdm/CTCE/login.html";

//单击行勾选checkbox事件
$(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
    var index = $(this).attr('data-index');
    var tableBox = $(this).parents('.layui-table-box');
    //存在固定列
    if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
        tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
    } else {
        tableDiv = tableBox.find(".layui-table-body.layui-table-main");
    }
    var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox i");
    if (checkCell.length>0) {
        checkCell.click();
    }
});
$(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
    e.stopPropagation();
});

/**
 * JS 方法拦截方法,只要返回false，后边的方法就不再执行
 * 调用示例 ：
 *         func = func.before(beforefn).after(afterfn);
 *         func();
 */
Function.prototype.before = function(beforefn){
    var _self = this;
    return function(data){
        if(beforefn.apply(this,arguments) === false){
            return false;
        }
        return _self.apply(this,arguments);
    }
}
Function.prototype.after = function(afterfn){
    var _self = this;
    return function(){
        var ret = _self.apply(this,arguments);
        if(ret === false){
            return false;
        }
        afterfn.apply(this,arguments);
        return ret;
    }
}


/* *
 * @Author bxf
 * @Description 公共ajax请求
 * @Date 9:56 2019/8/13
 * @param null
 * @return 
 */
var publicAjax = function(types,urls,params,asyncs,header,callback,error) {
    var async_val=true,header_val={"Authorization":getData("Authorization")},type_val='post';
    if(asyncs!=null){
        async_val = asyncs;
    }
    if(header!=null){
        header_val = header;
    }
    if(types!=null){
        type_val = types;
    }
	$.ajax({
		type: type_val,
		url: publicUrl + urls,
        headers:header_val,
		async:async_val,
		data:params,
        traditional: true,
        dataType:'json',
		success: function (data){
			if(data.code == 1017 || data.code == 1101){
                laybindevent(data.msg,2000,function(){
                    removeData("Authorization");
                    removeData("cacheflag");
                    window.location.href = loginUrl;
                });
			}else{
			    if(data.code == 2000){
			        var authorization = data.refreshToken;
                    if(authorization!=null && authorization!='' && authorization!='null'){
                        updateData("Authorization",authorization);
                    }
                }
                callback(data);
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
            if(error){
                error(XMLHttpRequest, textStatus, errorThrown);
            }
            layerror('内部错误，请联系管理员！');
		}
	});
}

/* *
 * @Author bxf
 * @Description 公共ajax请求
 * @Date 9:56 2019/8/13
 * @param null
 * @return
 */
var publicAjaxMap = function(types,urls,params,asyncs,header,callback,error) {
    var async_val=true,header_val={"Authorization":getData("Authorization")},type_val='post';
    if(asyncs!=null){
        async_val = asyncs;
    }
    if(header!=null){
        header_val = header;
    }
    if(types!=null){
        type_val = types;
    }
    var param = typeof(params)=='string'?params:JSON.stringify(params);
    $.ajax({
        type: type_val,
        url: publicUrl + urls,
        headers:header_val,
        async:async_val,
        data:param,
        contentType:'application/json',
        dataType:'json',
        traditional: true,
        success: function (data){
            if(data.code == 1017 || data.code == 1101){
                laybindevent(data.msg,2000,function() {
                    removeData("Authorization");
                    removeData("cacheflag");
                    window.location.href = loginUrl;
                });
            }else{
                if(data.code == 2000){
                    var authorization = data.refreshToken;
                    if(authorization!=null && authorization!='' && authorization!='null'){
                        updateData("Authorization",authorization);
                    }

                }
                callback(data);
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
            if(error){
                error(XMLHttpRequest, textStatus, errorThrown);
            }
            layerror('内部错误，请联系管理员！');
        }
    });
}
/* *
 * @Author bxf
 * @Description 公共ajax请求(对于new FormData())
 * @Date 9:56 2019/8/13
 * @param null
 * @return
 */
var publicAjaxFormData = function(types,urls,params,asyncs,header,callback,error) {
    var async_val=true,header_val={"Authorization":getData("Authorization")},type_val='post';
    if(asyncs!=null){
        async_val = asyncs;
    }
    if(header!=null){
        header_val = header;
    }
    if(types!=null){
        type_val = types;
    }
    $.ajax({
        type: type_val,
        url: publicUrl + urls,
        headers:header_val,
        async:async_val,
        data:params,
        contentType: false,
        processData: false,
        traditional: true,
        success: function (data){
            if(data.code == 1017 || data.code == 1101){
                laybindevent(data.msg,2000,function() {
                    removeData("Authorization");
                    removeData("cacheflag");
                    window.location.href = loginUrl;
                });
            }else{
                if(data.code == 2000){
                    var authorization = data.refreshToken;
                    if(authorization!=null && authorization!='' && authorization!='null'){
                        updateData("Authorization",authorization);
                    }
                }
                callback(data);
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
            if(error){
                error(XMLHttpRequest, textStatus, errorThrown);
            }
            layerror('内部错误，请联系管理员！');
        }
    });
}
/* *
 * @Author bxf
 * @Description 延迟执行
 * @Date 9:55 2019/8/27
 * @param null
 * @return
 */
var delayLoad = function(func,time){
    var times=2000;
    if(time){
        times = time;
    }
    setTimeout(func,times);
}

var loadbutton = function(id){
    var newid = "#buttongroup";
    if(id){
        newid = "#"+id;
    }
        var id = $(window.frameElement).attr('menuid');
        publicAjax(null,"sysmenu/selectById",{'id':id,'type':2},false,null,function(r){
            if(r.code==2000){
                var data = r.data;
                var buttonstr = "";
                $.each(data,function(i,e){
                    if(e.obj.length>0){
                        buttonstr += "<ul class='layui-bg-blue btnz' style='font-size: 12px;border-radius: 0px;float: left;padding:0px 0px 0px 0px;margin-left: 12px;'>"+
                            '<li class="layui-nav-item" style="line-height: 30px;font-size: 12px;">'+
                            "<a href='javascript:;' style='color:white;font-size: 12px;padding: 0px 10px 0px 10px;' class='buttondl'><i class='"+e.icon+"'></i>&nbsp;"+e.name+"&nbsp;<i class='layui-icon layui-icon-down'></i></a>"+
                            '<dl style="top: 44px; line-height: 31px; padding: 0px; display: block; position: absolute;display:none;z-index: 999;">';
                        $.each(e.obj,function(j,e1){
                            buttonstr += '<dd class="buttondd">'+
                                "<button type='button' class='layui-btn layui-btn-normal  layui-btn-fluid' onclick='"+e1.url+"'><i class='"+e1.icon+"'></i>"+e1.name+"</button>"+
                                '</dd>';
                        })
                        buttonstr += '</dl></li></ul>';
                    }else{
                        buttonstr += "<button type='button' style='float: left;margin-left: 12px' class='layui-btn layui-btn-normal' onclick='"+e.url+"'><i class='"+e.icon+"'></i>"+e.name+"</button>";
                    }
                })
                $(newid).html(buttonstr);
            }
        })
    $(".buttondl").live("click",function(){
        var flag = $(this).next().css("display");
        if(flag=='block'){
            $(this).next().css("display","none");
        }else{
            $(this).next().css("display","block");
        }
    })
    $(".buttondd").live("click",function(){
        $(this).parent().css("display","none");
    })
    $("button").live("click",function(){
        $(".buttondl").prev("dl").css("display","none");
    })
}
/* *
     * @Author bxf
     * @Description 操作失败
     * @Date 9:36 2019/8/13
     * @param msg ti
     * @return
     */
var layerror = function(msg,ti,event){
    layui.use('layer',function(){
        var layer = layui.layer;
        var message='操作失败',times=2000;
        if(msg){
            message=msg;
        }
        if(ti){
            times = ti;
        }
        if(event!=null){
            layer.msg(msg, {icon:5,time:times},event);
        }else{
            layer.msg(msg, {icon:5,time:times});
        }

    })

}
/* *
 * @Author bxf
 * @Description 操作成功
 * @Date 9:36 2019/8/13
 * @param msg ti
 * @return
 */
var laysuccess = function(msg,ti,event){
    layui.use('layer',function(){
        var layer = layui.layer;
        var message='操作成功',times=2000;
        if(msg){
            message=msg;
        }
        if(ti){
            times = ti;
        }
        if(event!=null){
            layer.msg(msg, {icon: 6,time:times},event);
        }else{
            layer.msg(msg, {icon: 6,time:times});
        }

    })

}
/* *
 * @Author bxf
 * @Description 自定义操作
 * @Date 9:36 2019/8/13
 * @param msg ti icon
 * @return
 */
var layself = function(msg,ti,ic){
    layui.use('layer',function(){
        var layer = layui.layer;
        var message='操作异常',times=2000,icons=3;
        if(msg){
            message=msg;
        }
        if(ti){
            times = ti;
        }
        if(ic){
            icons = ic;
        }
        layer.msg(msg, {icon:icons,time:times});
    })

}
/* *
* @Author bxf
* @Description 自定义操作绑定事件
* @Date 9:36 2019/8/13
* @param msg ti icon
* @return
*/
var laybindevent = function(msg,ti,event){
    layui.use('layer',function(){
        var layer = layui.layer;
        layer.msg(msg, {
            time: ti
        }, event)
    })
}
/* *
* @Author bxf
* @Description alert弹窗
* @Date 9:36 2019/8/13
* @param msg ti
* @return
*/
var alertself = function(msg,title,icon){
    layui.use('layer',function(){
        var layer = layui.layer;
        var message='操作成功',title='提示信息';
        if(msg){
            message=msg;
        }
        if(ti){
            ti = title;
        }
        if(icon){
            layer.alert(msg, {icon: icon,title:title});
        }else{
            layer.alert(msg, {title:title});
        }
    })
}
/* *
 * @Author bxf
 * @Description jsonobject序列化
 * @Date 12:36 2019/8/13
 * @param null
 * @return 
 */
$.fn.serializeJson = function () {
    var serializeObj = {};
    $(this.serializeArray()).each(function () {
        serializeObj[this.name] = $.trim(this.value);
    });
    return serializeObj;
};
/* *
 * @Author bxf
 * @Description sessionStorage保存数据
 * @Date 11:06 2019/8/21
 * @param null
 * @return
 */
var saveData = function(key,value){
    var time = 12*60*60*1000;
    var expiration = new Date().getTime() + time;
    store.set(key, value, expiration);

}
/* *
 * @Author bxf
 * @Description sessionStorage获取指定键的数据
 * @Date 11:08 2019/8/21
 */
var getData = function(key){
    return store.get(key);
}

// 检查cookie
var checkCookie = function(key) {
    username = getCookie(key);
    console.log(username);
    if (username != null && username != "")
    { return true; }
    else
    { return false;  }
}
/* *
 * @Author bxf
 * @Description sessionStorage删除指定键的数据
 * @Date 11:08 2019/8/21
 */
var removeData = function(key){
    store.remove(key);
}
/**
 * 更新sessionStorage中的值
 */
var updateData = function(key,value){
    store.remove(key);
    var time = 12*60*60*1000;
    var expiration = new Date().getTime() + time;
    store.set(key, value, expiration);
}

//查询字典
var getDic = function(code){
    var map=new Map();
    publicAjax ("post","/infdictitem/selectInfdictitemByInfdictsortCode",{"code":code},false
        ,null,function (r) {
            var data=r.data;
            for(var i=0;i<data.length;i++){
                map.set(data[i].code,data[i].name);
            }
        });
    return map;
}

/* *
 * @Author bxf
 * @Description 格式化table格式
 * @Date 14:55 2019/8/29
 * @param null
 * @return
 */
var formatTableParseData = function(res){
    if(res){
        if(res.code==1101){
            laybindevent(res.msg,1000,function() {
                window.location.href = loginUrl;
            });
        }else{
            var authorization = res.refreshToken;
            if(authorization!=null && authorization!='' && authorization!='null'){
                updateData("Authorization",authorization);
            }
            return {
                "code": res.code, //解析接口状态
                "count": res.data.total, //解析数据长度
                "msg": res.msg, //解析提示文本
                "data": res.data.list //解析数据列表
            };
        }
    }
}

/* *
 * @Author bxf
 * @Description 通用的树节点数据处理，func支持自定义函数
 * @Date 15:12 2019/8/29
 * @param null
 * @return 
 */
var formatTreeParseData = function(treeId,parentNode,responseData,func){
    var jsonsdata = responseData.data;
    if(responseData.code==1101){
        laybindevent(responseData.msg,1000,function() {
            window.location.href = loginUrl;
        });
    }else{
        var authorization = responseData.refreshToken;
        if(authorization!=null && authorization!='' && authorization!='null'){
            updateData("Authorization",authorization);
        }
        if(func!=null){
            return func(parentNode,responseData);
        }else{
            return jsonsdata;
        }
    }
}
/* *
 * @Author bxf
 * @Description 组织部分自定义icon
 * @Date 15:12 2019/8/29
 * @param null
 * @return
 */
var changeIcon = function(responseData){
    var newResponseData = new Array();
    $.each(responseData,function(i,e){
        switch (e.type){
            case 1:
                e.xIcon=publicResourceUrl+"common/images/Company.png";
                break;
            case 2:
                e.xIcon=publicResourceUrl+"common/images/department.png";
                break;
            case 3:
                e.xIcon=publicResourceUrl+"common/images/virtual_org.png";
                break;
            case 4:
                e.xIcon=publicResourceUrl+"common/images/project_dpt.png";
				break;
			case 5:
                e.xIcon=publicResourceUrl+"common/images/project.png";
				break;	
            default:
                e.xIcon=publicResourceUrl+"common/images/station.png";

        }
        newResponseData.push(e);
    })
    return newResponseData;
}


/**
 * 展开左侧菜单
 */
var openLeftMenu = function(){
    $('.left-nav').animate({width: '220px'}, 100);
    $('.page-content').animate({left: '220px'}, 100);
    $('.left-nav i').css('font-size','14px');
    $('.left-nav cite,.left-nav .nav_right').show();
    if($(window).width()<768){
        $('.page-content-bg').show();
    }
}
/**
 * 收缩左侧菜单
 */
var closeLeftMenu = function(){
    $('.left-nav .open').click();
    $('.left-nav i').css('font-size','18px');
    $('.left-nav').animate({width: '60px'}, 100);
    $('.left-nav cite,.left-nav .nav_right').hide();
    $('.page-content').animate({left: '60px'}, 100);
    $('.page-content-bg').hide();
}
/**/
var fullscreen = function() {
    /*全屏iframe兼容*/
    var docElm = document.documentElement;
    if (docElm.requestFullscreen) {
        docElm.requestFullscreen();
    } else if (docElm.mozRequestFullScreen) {
        docElm.mozRequestFullScreen();
    } else if (docElm.msRequestFullscreen) {
        docElm.msRequestFullscreen();
    } else if (docElm.oRequestFullscreen) {
        docElm.oRequestFullscreen();
    } else if (docElm.webkitRequestFullScreen) {
        docElm.webkitRequestFullScreen();
    }
    $(".container.layui-row").css("display", "none");
    $(".x-slide_left").css("display", "none");
    $(".left-nav").css("display", "none");
    $(".layui-tab-title").css("display", "none");
    $("iframe").css("height", "100%");
    $("iframe").css("width", "100%");
    $("iframe").css("position", 'fixed');
    $("iframe").css("left", "0px");
    $("iframe").css("top", "0px");

}
/*退出全屏iframe*/
function exitQ() {
    var mainheight = $('.left-nav').height();  //获取侧边菜单高度
    $(".container.layui-row").css("display", "");
    $(".left-nav").css("display", "");
    $(".layui-tab-title").css("display", "");
    $(".x-slide_left").css("display", "");
    //$("#site_info").css("display", "");
    //$("#full-screen-btn").css("display", "");
    var docElm = document.documentElement;
    /*退屏iframe兼容*/
    if (docElm.exitFullscreen) {
        docElm.exitFullscreen();
    } else if (docElm.msExitFullscreen) {
        docElm.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        docElm.mozCancelFullScreen();
    } else if (docElm.oRequestFullscreen) {
        docElm.oCancelFullScreen();
    } else if (docElm.webkitCancelFullScreen) {
        docElm.webkitCancelFullScreen();
    }
    $("iframe").css("height",mainheight + 'px');    //高度是侧边菜单高度，保持一致
    $("iframe").css("width", "");
    $("iframe").css("position", "");
    $("iframe").css("left", "");
    $("iframe").css("top", "");
}

//合并单元格
var merge = function(res,columsName,columsIndex) {
    var data = res.data;
    var mergeIndex = 0;//定位需要添加合并属性的行数
    var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
    var columsName = columsName;//需要合并的列名称
    var columsIndex = columsIndex;//需要合并的列索引值

    for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
        var trArr = $(".layui-table-body>.layui-table").find("tr");//所有行
        for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
            var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
            var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列

            if (data[i][columsName[k]] === data[i-1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                mark += 1;
                tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                    $(this).attr("rowspan", mark);
                });
                tdCurArr.each(function () {//当前行隐藏
                    $(this).css("display", "none");
                });
            }else {
                mergeIndex = i;
                mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
            }
        }
        mergeIndex = 0;
        mark = 1;
    }
}

//退出登录
function loginout() {
    layer.msg('退出登录成功', function () {
        removeData("Authorization");
        window.location = './login.html';
    });
};
//获取页面get传值
var getUrlParam = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}